<template>
  <div
    class="message-container"
    v-loading="isLoading"
    ref="messageContainerRef"
  >
    <MessageArea
      title="留言板"
      :subTitle="`(共 ${data.total || 0} 条评论)`"
      :list="data.rows"
      @submit="handlerSubmit"
      :isListLoding="loadingMore"
    />
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import featchData from "@/mixins/fetchData.js";
import { getMessage, addMessage } from "@/api/message.js";
export default {
  mixins: [featchData({})],
  name: "Message",
  components: {
    MessageArea,
  },
  data() {
    return {
      page: 1,
      limit: 10,
      loadingMore: false,
    };
  },
  mounted() {
    this.$refs.messageContainerRef.addEventListener(
      "scroll",
      this.handlerMessageListScroll
    );
  },
  beforeDestroy() {
    this.$refs.messageContainerRef.removeEventListener(
      "scroll",
      this.handlerMessageListScroll
    );
  },
  computed: {
    isHasmore() {
      return this.data.rows.length < this.data.total;
    },
  },
  methods: {
    async fetchData() {
      const res = await getMessage({ page: this.page, limit: this.limit });
      return res?.data || {};
    },
    async fetchMore() {
      if (this.isHasmore) {
        this.loadingMore = true;
        this.page++;
        const res = await this.fetchData();
        this.data.total = res?.total || 0;
        this.data.rows = this.data.rows.concat(res?.rows || []);
        this.loadingMore = false;
      }
    },
    async handlerSubmit(infoObj, callback) {
      const res = await addMessage(infoObj);
      if (res.code === 0) {
        this.data.rows.unshift(res?.data);
        this.$showMessage({
          content: "留言成功",
          type: "success",
        });
      }
      callback();
    },
    async handlerMessageListScroll(e) {
      if (this.loadingMore) {
        return;
      }
      let scrollHeight = e.target.scrollHeight;
      let scrollClientH = e.target.clientHeight;
      let scrollTop = e.target.scrollTop;
      if (scrollHeight - (scrollClientH + scrollTop) < 100) {
        this.fetchMore();
      }
    },
  },
};
</script>

<style scoped lang="less">
.message-container {
  padding: 10px;
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  box-sizing: border-box;
  overflow-y: auto;
  overflow-x: hidden;
}
</style>
